package cn.lichenes.service.impl;


import cn.lichenes.entity.Record;
import cn.lichenes.repository.RecordRepository;
import cn.lichenes.service.RecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.Date;

@Service
public class RecordServiceImpl implements RecordService {

    @Autowired
    private RecordRepository recordRepository;

    public void insert(Record record) {
        recordRepository.save(record);
    }

    public Page<Record> findAll(Integer page, Date beginTime, Date endTime) {
        PageRequest pageRequest = PageRequest.of(page - 1, 10, Sort.by(Sort.Direction.DESC, "rTime"));
        Specification<Record> specification = new Specification<Record>() {
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) {
                Predicate predicate = criteriaBuilder.between(root.get("rTime").as(Date.class),beginTime,endTime);
                return predicate;
            }
        };
        return recordRepository.findAll(specification,pageRequest);
    }
}
